<template>
  <div class="app-container">
    <el-form class="searchForm" ref="searchForm" :inline="true" :model="searchForm" label-width="68px" size="mini">
      <el-row>
        <el-col :span="4">
          <el-form-item label="设备编码">
            <el-input type="textarea" :rows="3" style="width: 120%"
              :placeholder="'请输入柜号，多个编码之间请回车换行，禁止输入特殊字符！输入示例：\nCC08DPC0202204250001\nCC08DPC0202205070001\n0000092011500063'"
              v-model="searchForm.codes" @change.native="keyUp($event)" @input.native="keyInput($event)">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="厂商" v-if="platformType == 'P'">
            <el-select v-model="searchForm.organizationId" placeholder="请选择厂商" @change="organizeChange" clearable>
              <el-option v-for="item in factuerOption" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运营商">
            <el-select :disabled="!searchForm.organizationId" v-model="searchForm.operatorId" placeholder="请先选择厂商" clearable>
              <el-option v-for="item in operatorOption" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备型号">
            <el-select v-model="searchForm.equipModeIds" multiple placeholder="请选择设备型号" clearable>
              <el-option v-for="item in modelOption" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="联网状态">
            <el-select v-model="searchForm.isOnline" placeholder="请选择联网状态" clearable>
              <el-option v-for="item in enumsJson.IS_ONLINE" :key="item.code" :label="item.label" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="业务状态">
            <el-select v-model="searchForm.status" placeholder="请选择业务状态" clearable>
              <el-option v-for="item in enumsJson.EQUIP_STATUS" :key="item.code" :label="item.label" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="事件内容">
            <el-input v-model="searchForm.name" placeholder="请输入事件内容" clearable></el-input>
          </el-form-item>
          
          <el-form-item label="地区" class="area-select">
            <el-cascader :options="areaSelectData" :props="areaSelectDataProps" ref="areaSelectRef" 
              v-model="searchForm.regionCode" placeholder="请选择省市区" @change="operateChange" clearable />
          </el-form-item>

          <el-form-item label="详细地址">
            <el-input v-model="searchForm.address" placeholder="请输入详细地址" clearable />
          </el-form-item>
          <el-form-item label="起止时间">
              <el-date-picker style="width: 340px;" :append-to-body="false" :popper-append-to-body="false" v-model="rangeDate" type="datetimerange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" clearable popper-class="tzy-popper">
              </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-search" @click="doSearch">搜索</el-button>
            <el-button type="default" size="mini" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <Table :tableHeader="tableHeader" :tableData="tableData" :tableLoading="listLoading">
      <template slot="codes" slot-scope="scope">
        <div class="codes">
          <span>{{ scope.row.equipCode }}</span>
          <img v-if="scope.row.isOnline == 1" src="@/assets/image/online.png" alt="" />
          <img v-else src="@/assets/image/offline.png" alt="" />
        </div>
      </template>
      <template slot="warning" slot-scope="scope">
        <span>{{ scope.row.flag ? "正常" : "故障" }}</span>
      </template>
    </Table>
    <pagination v-if="total > 0" :total="total" :page.sync="searchForm.pageNum" :limit.sync="searchForm.pageSize"
      @pagination="fetchData" />
  </div>
</template>

<script>
import { events } from "@/api/manage";
import { operator } from "@/api/factuer";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";

import { removeNullUndefined } from "@/utils/index.js";

import moment from "moment";
import { mapState } from "vuex";
export default {
  components: { Pagination, Table, Dialog },

  data() {
    return {
      listLoading: true,
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 15,
        name: "", //事件内容
        codes: "",
        organizationId: "",
        equipModeIds: [],
        operatorId: "",
        status: "",
        isOnline: "",
        regionCode: "",
        address: "",
        startTime: "",
        endTime: "",
      },
      rangeDate: [],

      tableHeader: [
        {
          type: "index",
          label: "序号",
          width: "60",
          fixed: true,
        },
        { slot: "codes", label: "设备编码",width:"250" },
        {
          label: "地址Id",
          prop: "addrId",
        },
        {
          label: "事件内容",
          prop: "semaphoreName",
        },
        {
          label: "运营商",
          prop: "operatorName",
        },
        {
          label: "型号",
          prop: "equipModelName",
        },
        {
          label: "升级结果",
          prop: "valueName",
        },
        {
          label: "上报时间",
          prop: "occurrenceTime",
          formatter: (item) => {
            return item.occurrenceTime
              ? moment(item.occurrenceTime).format("YYYY-MM-DD HH:mm:ss")
              : "";
          },
        },
      ],
      tableData: [],
      dialogForm: {
        name: "",
        code: "",
      },
      dialogRules: {
        name: [{ required: true, message: "请输入厂商名称", trigger: "blur" }],
        code: [
          { required: true, message: "请输入厂商编码", trigger: "blur" },
          { min: 10, max: 10, message: "厂商编码为10个字符", trigger: "blur" },
        ],
      },
      dialogTitle: "",

      areaSelectData: [], // options绑定的数据就是引入的 provinceAndCityData
      areaSelectDataProps: {
        children: "childrens",
        value: "code",
        label: "name",
        emitPath: false,
      },
      operatorOption: [], //运营商option
      factuerOption: [], //厂商option
      enumsJson: {},
      modelOption: [], //设备型号option
      platformType: this.$store.state.user.platformType,
      organizationId: this.$store.state.user.organizationId,
    };
  },
  computed: {
    ...mapState(["enums"]),
  },
  watch: {
    enums: {
      async handler(cur, old) {
        if (!old && Object.keys(cur).length == 0) {
          this.enumsJson = await this.$store.dispatch("enums/generateEnumMap");
        } else {
          this.enumsJson = this.$store.state.enums.enums;
        }
      },
      deep: true, //对象内部的属性监听，也叫深度监听
      immediate: true,
    },
  },
  async created() {
    if (this.platformType != "P") {
      //非平台用户
      this.searchForm.organizationId = this.organizationId;
      this.organizeChange(this.organizationId);
    } else {
      this.factuerOption = await this.$store.dispatch(
        "operator/generatorFactuer"
      );
    }
    this.fetchData();
    this.getOperator();
  },
  methods: {
    fetchData(val) {
      this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
      this.listLoading = true;
      let param = { ...this.searchForm };
      
      if (param.codes) {
        param.codes = param.codes.split("\n").filter(item=>item);
      }
      if(param.codes.length ==1){
        param.code = param.codes[0];
        delete param.codes;
      }
      if (this.rangeDate && this.rangeDate.length > 0) {
        param.startTime = this.rangeDate[0];
        param.endTime = this.rangeDate[1];
      }
      events(
        "/list",
        "post",
        {
          ...removeNullUndefined(param),
        },
        1
      )
        .then((res) => {
          this.tableData = res.data;
          this.total = +res.total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    async getOperator() {
      this.areaSelectData = await this.$store.dispatch(
        "operator/generatorRegion"
      );
      this.modelOption = await this.$store.dispatch("operator/generatorModel");
    },
    async organizeChange(e) {
      this.operatorOption = [];
      this.searchForm.operatorId = "";
      if(e){
      let datas = await operator("/all", "get", { organizationId: e });
      this.operatorOption = datas.data;
      }
    },

    operateChange(e) {
    },

    //限制输入特殊字符
    keyUp(e) {
      let str = e.target.value.replace(
        /[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
        ""
      );
      e.target.value = str;
      this.searchForm.codes = str;
    },
    // 只能输入汉字、英文、数字
    keyInput(e) {
      let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
      e.target.value = str;
      this.searchForm.codes = str;
    },
    resetSearch() {
      this.searchForm = {
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        name: "", //事件内容
        codes: "",
        organizationId: "",
        equipModeIds: [],
        operatorId: "",
        status: "",
        isOnline: "",
        regionCode: "",
        address: "",
        startTime: "",
        endTime: "",
      };
      this.rangeDate = [];
    },
    doSearch() {
      this.searchForm.pageNum = 1;
      this.fetchData();
    },
  },
};
</script>
<style lang="scss">
.el-date-editor .el-range-separator,
.el-date-editor .el-range__icon {
  line-height: 24px;
}
</style>
<style scoped lang="scss">
@import "@/styles/common.scss";

.area-select {
  .el-cascader {
    width: 100%;
  }
}

.filters {
  .el-form-item__content {
    width: auto;
  }
}
.searchForm{
  .el-form-item{
    margin-bottom: 8px;
  }
}
.codes {
  @include flexLayout(center, center);

  img {
    width: 20px;
    margin-left: 10px;
  }
}
::v-deep .tzy-popper{
    margin-left: -50px;
}
</style>